var db = require( '../db/db' );

const tableName = 'core.user_plan';

exports.getByUserId = async function ( userId ) {
    var sql = `select * from ${ tableName } where user_id=$1`;
    var params = [ userId ];

    try {

        var result = await db.runSql( sql, params );

        if ( result ) {
            return result.rows;
        }
        return null;

    } catch ( e ) {
        console.error( "查询方案出错" );
        return null;
    }
}

exports.getCurrentPlan = async function ( userId ) {
    // var sql = `select * from ${ tableName } where user_id= $1 and status=1 and date_trunc('day', end_at)>=current_date and date_trunc('day', start_at)<=current_date limit 1`;
    var sql = `SELECT plan, start_at, end_at FROM 
	(SELECT plan, start_at FROM ${ tableName } where user_id= $1  and status=1 and date_trunc('day', end_at)>=current_date order by start_at asc) as user_plan_start, 
	(SELECT end_at FROM ${ tableName } where user_id= $1  and status=1 and date_trunc('day', end_at)>=current_date order by end_at desc) as user_plan_end limit 1;`;
    
    var params = [ userId ];

    try {

        var result = await db.runSql( sql, params );

        if ( result ) {
            return result.rows;
        }
        return null;

    } catch ( e ) {
        console.error( "查询方案出错" );
        return null;
    }
}

